import { Form, Input, message, Modal } from "antd"
import { useImperativeHandle, useState } from "react"
import { useRequest } from "umi"

interface PropsType {
  cRef: any,
  submit: () => void,
}
interface dataType {
  courseName: string,
  endSection: number,
  startSection: number,
  weeks: number,
  id: number
}

const EditForm: React.FC<PropsType> = ({ cRef, submit }) => {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [typeModal, setTypeModal] = useState(1)
  const [formId, setFormId] = useState<number | null>(null)
  const [form] = Form.useForm()

  useImperativeHandle(cRef, () => ({
    open: (type: number, data?: dataType) => {
      if (data) {
        form.setFieldsValue(data)
        setFormId(data.id)
      }
      setTypeModal(type)
      setIsModalVisible(true)
    }
  }))

  const { run: addApi, loading: addLoading } = useRequest((data) => ({
    url: '/api/course/create',
    method: 'post',
    data
  }), { manual: true })

  const { run: updateApi, loading: updateLoading } = useRequest((data) => ({
    url: '/api/course/update',
    method: 'post',
    data
  }), { manual: true })

  const handleOk = () => {
    form.validateFields().then(async values => {
      if (typeModal === 1) {
        await addApi(values)
      } else {
        await updateApi({...values, id: formId})
      }
      submit()
      message.success('操作成功')
      setIsModalVisible(false);
      form.resetFields();
    }).catch(() => { })
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };
  return <Modal
    title={typeModal === 1 ? "新增" : "修改"}
    visible={isModalVisible}
    onOk={handleOk}
    onCancel={handleCancel}
    confirmLoading={addLoading || updateLoading}
  >
    <Form
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      autoComplete="off"
    >
      <Form.Item label="课程名" name="courseName" rules={[{ required: true }]}>
        <Input maxLength={20} />
      </Form.Item>
      <Form.Item label="开始节次" name="startSection" rules={[{ required: true }]}>
        <Input type='number' maxLength={2} />
      </Form.Item>
      <Form.Item label="结束节次" name="endSection" rules={[{ required: true }]}>
        <Input type='number' maxLength={2} />
      </Form.Item>
      <Form.Item label="星期" name="weeks" rules={[{ required: true }]}>
        <Input type='number' maxLength={1} />
      </Form.Item>
    </Form>
  </Modal>
}

export default EditForm